<?php

/**
 * @Author: Wang Chunsheng 2192138785@qq.com
 * @Date:   2020-03-10 20:37:35
 * @Last Modified by:   Wang Chunsheng 2192138785@qq.com
 * @Last Modified time: 2020-03-12 17:29:43
 */



namespace app\modules\wechat\components;

use api\models\DdApiAccessToken;
use Yii;
use api\models\DdMember;
use api\modules\wechat\models\DdWxappFans;
use common\helpers\ErrorsHelper;
use common\helpers\StringHelper;
use yii\base\BaseObject;
use yii\data\Pagination;

use function GuzzleHttp\json_decode;

class Fans extends BaseObject
{
    /**
     * 注册fans数据.
     *
     * @param int|null post
     * @return string
     * @throws NotFoundHttpException
     */
    public function signup($users)
    {
        $openid   = $users['openid'];
        $nickname = $users['nickname'];
        $keys = $openid . '_userinfo';
        if (Yii::$app->cache->get($keys)) { //如果有缓存数据则返回缓存数据，没有则从数据库取病存入缓存中
            // 获取缓存
            $res = Yii::$app->cache->get($keys);
            // 验证有效期
            $isPeriod = Yii::$app->service->apiAccessTokenService->isPeriod($res['access_token']);
            if (!$isPeriod) {
                return Yii::$app->cache->get($keys);
            }
        }
        $DdMember = new DdMember();
        // 校验openID是否存在
        $isHave = $this->checkByopenid($openid);
        if ($isHave) {
            $fans =  $this->fansByopenid($openid);
            $member = $DdMember::findIdentity($fans['user_id']);
            $userinfo = Yii::$app->service->apiAccessTokenService->getAccessToken($member, 1);
            $userinfo['fans'] = $this->fansByopenid($openid);
            Yii::$app->cache->set($keys, $userinfo);
            return $userinfo;
        } else {

            $password = StringHelper::randomNum();
            $res = $DdMember->signup($nickname, 0, $password);
            // 更新openid
            $member_id = $res['member']['member_id'];
            $DdMember->updateAll(['openid' => $openid], ['member_id' => $member_id]);
            DdApiAccessToken::updateAll(['openid' => $openid], ['member_id' => $member_id]);
            // 注册fans
            // 生成随机的加密键
            $secretKey = Yii::$app->getSecurity()->generateRandomString();
            $dataFans = [
                'user_id' => $member_id,
                'avatarUrl' => $users['avatarUrl'],
                'openid'   => $users['openid'],
                'nickname' => $users['nickname'],
                'groupid' => $res['member']['groupid'],
                'fans_info' => $users['openid'],
                'unionid' => $users['unionid'],
                'gender' => $users['gender'],
                'country' => $users['country'],
                'city' => $users['city'],
                'province' => $users['province'],
                'secretKey' => $secretKey
            ];
            // 加密fans的所有资料
            $dataFans['fans_info'] = $this->encrypt($dataFans, $secretKey);
            $DdWxappFans  = new DdWxappFans();
            $DdWxappFans->load($dataFans, '');
            $DdWxappFans->save();
            $errors = ErrorsHelper::getModelError($DdWxappFans);
            if (!empty($errors)) {
                return $errors;
            }
            $res['fans'] = $dataFans;
            Yii::$app->cache->set($keys, $res);
            return $res;
        }
    }

    public function checkByopenid($openid)
    {
        return  DdWxappFans::findOne(['openid' => $openid]);
    }

    public function fansByopenid($openid)
    {
        return  DdWxappFans::findOne(['openid' => $openid]);
    }

    /**
     *
     * @param string $string 需要加密的字符串
     * @param string $key 密钥
     * @return string
     */
    public static function encrypt($data, $key)
    {
        $string = base64_encode(json_encode($data));
        // openssl_encrypt 加密不同Mcrypt，对秘钥长度要求，超出16加密结果不变
        $data = openssl_encrypt($string, 'AES-128-ECB', $key, OPENSSL_RAW_DATA);

        $data = strtolower(bin2hex($data));

        return $data;
    }


    /**
     * @param string $string 需要解密的字符串
     * @param string $key 密钥
     * @return string
     */
    public static function decrypt($string, $key)
    {

        $decrypted = openssl_decrypt(hex2bin($string), 'AES-128-ECB', $key, OPENSSL_RAW_DATA);
        return json_decode(base64_decode($decrypted));
    }
}
